package com.example.demo.common;

import org.springframework.stereotype.Service;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Potato  on 2016/11/17.
 * AbstractService  Implement By MyBatis
 * 基于通用Mapper的MyBatis来实现Service接口的抽象Service
 */
@Service
public abstract class AbstractService<T> implements BaseService<T> {

    public abstract BaseMapper<T> getMapper();

    private Class<T> modelClass;    // 当前泛型真实类型的Class

    public AbstractService() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public void save(T entity) {
        getMapper().insert(entity);
    }

    @Override
    public void delete(T entity) {
        // TODO Auto-generated method stub
        getMapper().delete(entity);
    }

    @Override
    public void update(T entity) {
        // TODO Auto-generated method stub
        getMapper().updateByPrimaryKey(entity);
    }

    @Override
    public T findById(int id) {
        // TODO Auto-generated method stub
        return getMapper().selectByPrimaryKey(id);
    }

    @Override
    public List<T> getAll() {
        // TODO Auto-generated method stub
        return getMapper().selectAll();
    }

}

